package view.Validator;

import javafx.scene.control.Control;
import javafx.scene.control.TextField;

import org.controlsfx.validation.ValidationResult;
import org.controlsfx.validation.Validator;

/**
 * Provides a <code>Validator</code> that checks the range of a given double input.
 * In order to use this Validator one of the factory methods must be invoked.
 * 
 * @version %I%, %G%
 *
 */
public final class DoubleNumberRangeValidator implements Validator<String> {

	private double min;
	private double max;
	
	private DoubleNumberRangeValidator(double min, double max){
		this.min = min;
		this.max = max;
	}
	
	public static DoubleNumberRangeValidator createNumberRangeValidator(double min, double max){
		return new DoubleNumberRangeValidator(min, max);
	}
	
	public static DoubleNumberRangeValidator createMinNumberRangeValidator(double min){
		return new DoubleNumberRangeValidator(min, Double.MAX_VALUE);
	}
	
	public static DoubleNumberRangeValidator createMaxNumberRangeValidator(double max){
		return new DoubleNumberRangeValidator(Double.MIN_VALUE, max);
	}
	
	@Override
	public ValidationResult apply(Control t, String u) {
		ValidationResult res = new ValidationResult();
		final String MSGRANGE = "Es muss eine Zahl zwischen " + min + " und " + max + " eingegeben werden.\nDezimalzahlen muessen mit einem '.' getrennt werden.";

		if (t instanceof TextField) {
			try {
				if(((TextField) t).getText().equals("")){
					return res;
				}
				double input = Double.valueOf(((TextField) t).getText());
				boolean isInRange = input >= min && input <= max;
				if (!isInRange) {
					res.addErrorIf(t, MSGRANGE, true);
				} else if (input == 0) {
					res.addWarningIf(t,
							"Achtung moeglicherweise falsche Eingabe.", true);
				}
			} catch (NumberFormatException e) {
				res.addErrorIf(t, MSGRANGE, true);
			}
		}
		return res;
	}
}
